package com.lzc.security.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.security.Principal;

@Controller
public class IndexController {

    @GetMapping("/index.html")
    public ModelAndView index() {
        return new ModelAndView("index");
    }

    @GetMapping("/index2.html")
    public ModelAndView index2() {
        return new ModelAndView("index2");
    }

    @PreAuthorize("hasRole('ROLE_USER')")
    @GetMapping("/user")
    @ResponseBody
    public Object user(Principal principal) {
        return principal;
    }

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping("/admin")
    @ResponseBody
    public Object admin(Principal principal) {
        return principal;
    }

    @PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER') and principal.username.equals(#username)")
    @GetMapping("/test/{username}")
    @ResponseBody
    public Object test(@PathVariable String username) {
        return "Hello test";
    }
}
